/**
 * Request 工具使用示例
 * 展示如何使用彻底封装的 request.ts 工具
 */

import {
  getData,
  postData,
  putData,
  patchData,
  deleteData,
  postFile,
  download,
  batchRequest,
  concurrentRequest,
  cachedRequest,
  isSuccess,
  isError,
  extractData,
  extractError,
  createRequestConfig,
  createRequestOptions,
  requestController,
  requestCache,
  requestStats,
  ApiResponse,
} from './request';

// 示例数据类型
interface User {
  id: number;
  name: string;
  email: string;
}

interface UserListResponse {
  users: User[];
  total: number;
}

/**
 * 基础请求示例
 */
export const basicRequestExamples = {
  // GET 请求示例
  async fetchUsers(): Promise<User[]> {
    const response = await getData<UserListResponse>('/users');
    if (isSuccess(response)) {
      return extractData(response)?.users || [];
    }
    throw new Error(extractError(response));
  },

  // POST 请求示例
  async createUser(userData: Partial<User>): Promise<User> {
    const response = await postData<User>('/users', userData);
    if (isSuccess(response)) {
      return extractData(response)!;
    }
    throw new Error(extractError(response));
  },

  // PUT 请求示例
  async updateUser(id: number, userData: Partial<User>): Promise<User> {
    const response = await putData<User>(`/users/${id}`, userData);
    if (isSuccess(response)) {
      return extractData(response)!;
    }
    throw new Error(extractError(response));
  },

  // PATCH 请求示例
  async patchUser(id: number, updates: Partial<User>): Promise<User> {
    const response = await patchData<User>(`/users/${id}`, updates);
    if (isSuccess(response)) {
      return extractData(response)!;
    }
    throw new Error(extractError(response));
  },

  // DELETE 请求示例
  async deleteUser(id: number): Promise<boolean> {
    const response = await deleteData(`/users/${id}`);
    return isSuccess(response);
  },
};

/**
 * 高级功能示例
 */
export const advancedRequestExamples = {
  // 带配置的请求
  async fetchUsersWithConfig(): Promise<User[]> {
    const config = createRequestConfig({
      timeout: 30000,
      retryCount: 5,
      retryDelay: 2000,
    });

    const options = createRequestOptions({
      config,
      headers: {
        'X-Custom-Header': 'value',
      },
    });

    const response = await getData<UserListResponse>('/users', {}, options);
    return extractData(response)?.users || [];
  },

  // 文件上传示例
  async uploadAvatar(userId: number, file: File): Promise<string> {
    const formData = new FormData();
    formData.append('avatar', file);
    formData.append('userId', userId.toString());

    const response = await postFile<{ url: string }>('/upload/avatar', formData);
    if (isSuccess(response)) {
      return extractData(response)?.url || '';
    }
    throw new Error(extractError(response));
  },

  // 文件下载示例
  async downloadReport(reportId: string): Promise<void> {
    const blob = await download('/reports/download', { reportId });
    if (blob instanceof Blob) {
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `report_${reportId}.pdf`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    }
  },

  // 批量请求示例
  async fetchUserData(userIds: number[]): Promise<User[]> {
    const requests = userIds.map(id => () => getData<User>(`/users/${id}`));
    const responses = await batchRequest(requests);
    
    return responses
      .filter(isSuccess)
      .map(extractData)
      .filter((user): user is User => user !== null);
  },

  // 并发请求示例（限制并发数）
  async fetchUsersConcurrently(userIds: number[], concurrency: number = 3): Promise<User[]> {
    const requests = userIds.map(id => () => getData<User>(`/users/${id}`));
    const responses = await concurrentRequest(requests, concurrency);
    
    return responses
      .filter(isSuccess)
      .map(extractData)
      .filter((user): user is User => user !== null);
  },

  // 缓存请求示例
  async fetchCachedUsers(): Promise<User[]> {
    const cacheKey = 'users_list';
    const ttl = 5 * 60 * 1000; // 5分钟缓存

    const response = await cachedRequest(
      cacheKey,
      () => getData<UserListResponse>('/users'),
      ttl
    );

    return extractData(response)?.users || [];
  },
};

/**
 * 请求控制示例
 */
export const requestControlExamples = {
  // 可取消的请求
  async cancellableRequest(): Promise<void> {
    const requestId = 'fetch_users';
    const controller = requestController.create(requestId);

    try {
      const response = await getData('/users', {}, {
        signal: controller.signal,
      });
      console.log('请求成功:', response);
    } catch (error) {
      if (error.name === 'AbortError') {
        console.log('请求被取消');
      } else {
        console.error('请求失败:', error);
      }
    }
  },

  // 取消请求
  cancelRequest(requestId: string): void {
    requestController.cancel(requestId);
  },

  // 取消所有请求
  cancelAllRequests(): void {
    requestController.cancelAll();
  },
};

/**
 * 缓存管理示例
 */
export const cacheManagementExamples = {
  // 手动设置缓存
  setUserCache(userId: number, user: User): void {
    requestCache.set(`user_${userId}`, user, 10 * 60 * 1000); // 10分钟
  },

  // 手动获取缓存
  getUserCache(userId: number): User | null {
    return requestCache.get(`user_${userId}`);
  },

  // 删除特定缓存
  deleteUserCache(userId: number): void {
    requestCache.delete(`user_${userId}`);
  },

  // 清空所有缓存
  clearAllCache(): void {
    requestCache.clear();
  },

  // 清理过期缓存
  cleanupExpiredCache(): void {
    requestCache.cleanup();
  },
};

/**
 * 请求统计示例
 */
export const requestStatsExamples = {
  // 获取统计信息
  getStats() {
    return requestStats.getStats();
  },

  // 重置统计
  resetStats(): void {
    requestStats.reset();
  },

  // 模拟记录请求统计
  recordRequest(responseTime: number, success: boolean): void {
    requestStats.record(responseTime, success);
  },
};

/**
 * 错误处理示例
 */
export const errorHandlingExamples = {
  // 统一错误处理
  async handleRequestWithErrorHandling(): Promise<User[]> {
    try {
      const response = await getData<UserListResponse>('/users');
      
      if (isSuccess(response)) {
        return extractData(response)?.users || [];
      } else {
        // 处理业务错误
        const errorMsg = extractError(response);
        console.error('业务错误:', errorMsg);
        throw new Error(errorMsg);
      }
    } catch (error) {
      // 处理网络错误或其他异常
      console.error('请求异常:', error);
      throw error;
    }
  },

  // 重试机制示例
  async retryableRequest(): Promise<User[]> {
    const config = createRequestConfig({
      retryCount: 3,
      retryDelay: 1000,
    });

    const response = await getData<UserListResponse>('/users', {}, {
      config,
    });

    return extractData(response)?.users || [];
  },
};

/**
 * 实际使用场景示例
 */
export const realWorldExamples = {
  // 用户管理页面
  async loadUserManagementPage(): Promise<{
    users: User[];
    stats: any;
  }> {
    // 并行加载用户列表和统计信息
    const [usersResponse, statsResponse] = await Promise.all([
      getData<UserListResponse>('/users'),
      getData('/users/stats'),
    ]);

    return {
      users: extractData(usersResponse)?.users || [],
      stats: extractData(statsResponse) || {},
    };
  },

  // 表单提交
  async submitUserForm(formData: Partial<User>): Promise<User> {
    const response = await postData<User>('/users', formData, {}, {
      config: {
        showLoading: true,
        showError: true,
      },
    });

    if (isSuccess(response)) {
      return extractData(response)!;
    }

    throw new Error(extractError(response));
  },

  // 数据同步
  async syncUserData(): Promise<void> {
    // 清理旧缓存
    requestCache.clear();

    // 重新获取数据
    const response = await getData<UserListResponse>('/users');
    
    if (isSuccess(response)) {
      const users = extractData(response)?.users || [];
      
      // 缓存用户数据
      users.forEach(user => {
        requestCache.set(`user_${user.id}`, user, 5 * 60 * 1000);
      });
    }
  },
};

// 导出所有示例
export default {
  basicRequestExamples,
  advancedRequestExamples,
  requestControlExamples,
  cacheManagementExamples,
  requestStatsExamples,
  errorHandlingExamples,
  realWorldExamples,
};
